package com.haowan123.qinmeiren.appota2;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.mylib.Interface;
import com.origamilabs.library.views.StaggeredGridView;

public class ListImageView extends Activity {

	private StaggeredGridView staggeredCollection;
	private TextView downloadBtn;
	private TextView downloadIndicator;
	private SeekBar downloadProgress;
	private Handler handler=new Handler();
	private Interface helper;
	private double currentByte;
	private double totalBytes;
	private ProgressDialog loading;
	private int stt;
	private ProgressObserver observer = new ProgressObserver();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.e("","Oncreate");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_image_view);
		staggeredCollection = (StaggeredGridView)findViewById(R.id.staggeredCollection);
		staggeredCollection.setItemMargin(10); // set the GridView margin
		staggeredCollection.setPadding(10, 0, 10, 0); // have the margin on the sides as well 
		CollectionStaggeredAdapter adapter = new CollectionStaggeredAdapter(this, R.id.staggeredCollection, new String[]{""});
		staggeredCollection.setAdapter(adapter);
		staggeredCollection.setOnItemClickListener(new StaggeredGridView.OnItemClickListener() {
			
			@Override
			public void onItemClick(StaggeredGridView parent, View view, int position,
					long id) {
				Intent full = new Intent(ListImageView.this, FullScreenshotImageActivity.class);
				full.putExtra(Constants.IMAGE_POSITION, position);
				Log.e("","open image index "+position);
				full.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
				startActivity(full);
				overridePendingTransition(R.anim.bottom_to_up_in,0); 
			}
		});
		adapter.notifyDataSetChanged();
		loading=new ProgressDialog(this);
		loading.setMessage(getResources().getString(R.string.loading));
		loading.setCancelable(false);
		downloadProgress=(SeekBar)findViewById(R.id.downloadProgress);
		downloadProgress.setMax(100);
		downloadProgress.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				return true;
			}});
		downloadBtn=(TextView) findViewById(R.id.downloadBtn);
		downloadIndicator=(TextView) findViewById(R.id.downloadIndicator);
		downloadBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(stt==1){
					if(CommonUtils.isFileAvaiable(ListImageView.this)){
						//show open file or delete file
						AlertDialog.Builder builder=new Builder(ListImageView.this);
						builder.setMessage(getResources().getString(R.string.file_avaiable)).setPositiveButton(getResources().getString(R.string.redownload), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								if(CommonUtils.checkNetworkAvaliable(ListImageView.this)){
									dialog.dismiss();
									if(CommonUtils.deleteOldFile()){
										doGetPics();
									}
									else{
										Toast.makeText(ListImageView.this, getResources().getString(R.string.delete_error), Toast.LENGTH_SHORT).show();
									}
								}else{
									Toast.makeText(ListImageView.this, getResources().getString(R.string.check_network), Toast.LENGTH_SHORT).show();
								}
							}
						}).setNegativeButton(getResources().getString(R.string.open), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								Intent sintent = new Intent(Intent.ACTION_VIEW);
						    	sintent.setDataAndType(Uri.fromFile(new File(Constants.PATH)),"application/vnd.android.package-archive");
						    	sintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						    	startActivity(sintent);
							}
						}).setCancelable(false).show();
					}else{
						downloadBtn.setVisibility(View.GONE);
						downloadProgress.setVisibility(View.VISIBLE);
						doDownload();
					}
					
				}else if(stt==-1){
					performCheckingDownload();
				}
			}
		});
		helper= UIApp.getHelper();
		IntentFilter filter=new IntentFilter();
		filter.addAction(Constants.UPDATE_PROGRESS_ACTION);
		filter.addAction(Constants.DOWNLOAD_COMPLETE_ACTION);
		registerReceiver(observer, filter);
		stt=UIApp.getSTT();
		Log.e("status","stt:"+stt);
		//dismiss loading dialog if able
		if(stt!=-1){
			loading.dismiss();
			if(stt==1){
				downloadBtn.setText(getResources().getString(R.string.lbl_app));
			}else if(stt==0){
				downloadBtn.setText(getResources().getString(R.string.lbl));
			}
		}
	}

	@Override
	protected void onDestroy() {
		Log.e("","onDestroy");
		unregisterReceiver(observer);
		super.onDestroy();
	}
	
	private void performCheckingDownload() {
		if(CommonUtils.checkNetworkAvaliable(this)){
			doGetPics();
		}else{
			AlertDialog.Builder builder=new Builder(this);
			builder.setMessage(getResources().getString(R.string.check_network)).setPositiveButton(getResources().getString(R.string.retry), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					if(CommonUtils.checkNetworkAvaliable(ListImageView.this)){
						dialog.dismiss();
						doGetPics();
					}
				}
			}).setNegativeButton(getResources().getString(R.string.exit), new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			}).setCancelable(false).show();
		}
	}
	
	private void doGetPics() {
		loading.show();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				if(stt!=-1){
					if(gotData){
						return;
					}
					if(loading!=null&&loading.isShowing()){
						loading.dismiss();
					}
					if(stt==1){
						downloadBtn.setText(getResources().getString(R.string.lbl_app));
						downloadBtn.setVisibility(View.GONE);
						downloadProgress.setVisibility(View.VISIBLE);
						doDownload();
						UIApp.setSTT(1);
					}
				}else{
					handler.postDelayed(this,2000);
				}
			}
		}, 3000);
		stt=helper.init(CommonUtils.getDeviceId(this), getApplicationContext().getPackageName(), CommonUtils.sdCardPath());
		Log.e("status","stt:"+stt);
		//dismiss loading dialog if able
		if(stt!=-1){
			gotData=true;
			if(loading!=null&&loading.isShowing()){
				loading.dismiss();
			}
			
			if(stt==1){
				downloadBtn.setText(getResources().getString(R.string.lbl_app));
				downloadBtn.setVisibility(View.GONE);
				downloadProgress.setVisibility(View.VISIBLE);
				doDownload();
				UIApp.setSTT(1);
			}else{
				UIApp.setSTT(0);
			}
		}
	}
	private boolean gotData=false;
	
	private class ProgressObserver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(Constants.UPDATE_PROGRESS_ACTION)){
				currentByte=intent.getDoubleExtra(Constants.CURRENT_PROGRESS, 0f);
				totalBytes=intent.getDoubleExtra(Constants.TOTAL_PROGRESS, 1f);
				updateDownloadProgress(currentByte, totalBytes);
			}else{
				if(!UIApp.canOpenfile()){
					return;
				}
				finishDownload();
			}
		}
    	
    }
	
	public void updateDownloadProgress(double currentbyte,double totalbytes){
    	if(currentbyte==totalbytes){
    		//finish download
    		downloadProgress.setProgress(0);
    		downloadProgress.setVisibility(View.GONE);
    		downloadBtn.setVisibility(View.VISIBLE);
    		downloadIndicator.setText("");
    		Toast.makeText(ListImageView.this, "Download finished", Toast.LENGTH_SHORT).show();
    	}else{
    		if(totalbytes!=0){
    			downloadBtn.setVisibility(View.GONE);
				downloadProgress.setVisibility(View.VISIBLE);
    			downloadProgress.setProgress((int) (currentbyte*100/totalbytes));
    			downloadIndicator.setText(getResources().getString(R.string.download_indicator, (int) (currentbyte*100/totalbytes)));
    		}
    	}
    	
    }
    public void finishDownload(){
    	Intent intent = new Intent(Intent.ACTION_VIEW);
    	intent.setDataAndType(Uri.fromFile(new File(Constants.PATH)),"application/vnd.android.package-archive");
    	startActivity(intent);
    }

	private void doDownload() {
		Intent dl=new Intent(this, DownloadService.class);
		dl.setAction("DLA");
		UIApp.allowOpenForNewDownload();
		startService(dl);
	}
    
}
